package com.liyiwei.springext.importAnnotation.config;

import com.alibaba.fastjson.JSONObject;
import com.liyiwei.springext.importAnnotation.annotation.PayClient;
import com.liyiwei.springext.importAnnotation.annotation.PayParams;
import com.liyiwei.springext.importAnnotation.bean.TestFactory;
import lombok.Data;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Data
public class PayFactoryBean<T> implements FactoryBean {

    private Integer payId;

    private Class<T> interfaceType;


    @Override
    public Object getObject() throws Exception {
        //这里主要是创建接口对应的实例，便于注入到spring容器中
        InvocationHandler handler = new ServiceProxy<>(interfaceType);
        return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(),
                new Class[] {interfaceType},handler);
    }

    @Override
    public Class<?> getObjectType() {
        return TestFactory.class;
    }
}

class ServiceProxy<T> implements InvocationHandler{
    private Class<T> interfaceType;

    public ServiceProxy(Class<T> intefaceType) {
        this.interfaceType = interfaceType;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        /**
         * 在使用反射对象时比如Method和Field的getDeclaringClass方法将获取到所属类对象
         */
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this,args);
        }

        PayClient payClient = method.getAnnotation(PayClient.class);
        int type = payClient.type();
        System.out.println(type);
        return null;

    }
}
